﻿using CaseManagerLibrary.DB.SQLite;
using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using Newtonsoft.Json;
using PSDClientService.SystemSettings;
using PSDLib.Models;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PSDClientService.Download
{
    public class ErrorFileManager_v2
    {
        private DownloadContext context;
        private Thread errorFileThread = null;
        private SQLiteHelper sqlite;
        private SQLiteConnection conn;
        private static object lock_conn = new object();

        private bool paused = false;
        public bool Enabled { get; set; }
        public ErrorFileManager_v2(DownloadContext ctx)
        {
            context = ctx;
        }

        public bool Init()
        {
            paused = false;
            Enabled = true;
            //string file = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "PSD", "Data", "errorfiles.db");

            //Enabled = System.IO.File.Exists(file);

            if (Enabled)
            {
                //sqlite = new SQLiteHelper();
                //sqlite.FileName = file;

                errorFileThread = new Thread(new ThreadStart(RetryErrorFile));
                errorFileThread.Start();
            }

            return Enabled;
        }

        public void Pause()
        {
            paused = true;
        }

        public void Continue()
        {
            paused = false;
        }

        public void RetryErrorFile()
        {
            while (context.Running && Enabled)
            {
                if (context.Downloading && !paused)
                {
                    var data = new Dictionary<string, string>();
                    data.Add("deviceId", context.Device.id);
                    var result = HttpHelper.Post<HResult<int>>(AppSettings.Setting.API.RetryDownloadErrorFiles, data);

                    if (result.success && result.data == 1)
                    {
                        context.DownloadManager.GetDownloadWaitingFiles();
                    }
                }

                Thread.Sleep(1000 * 60 * 30);
            }
        }

        public void AddErrorFile(error_files file)
        {
            //do nothing
        }

        public void IngoreErrorFile(List<string> ignoreList)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.IgnoreDownloadFail, JsonConvert.SerializeObject(ignoreList));
        }


        public void Dispose()
        {
            Enabled = false;

            try
            {
                if (errorFileThread != null)
                {
                    errorFileThread.Abort();
                }
            }
            catch
            { }
        }
    }
}
